<template>
  <div class="home-container">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <h2>SRP文件处理系统</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :src="userStore.userInfo.avatar" />
              <span class="username">{{ userStore.userInfo.name || userStore.userInfo.username }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">用户信息管理</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主内容区 -->
      <el-main class="main-content">
        <!-- 操作按钮区 -->
        <div class="operation-section">
          <el-space :size="20">
            <el-button type="primary" size="large" @click="showUploadDialog('single')">
              <el-icon><Upload /></el-icon>
              单文件上传
            </el-button>
            <el-button type="success" size="large" @click="showUploadDialog('multiple')">
              <el-icon><Upload /></el-icon>
              多文件上传
            </el-button>
            <el-button type="warning" size="large" @click="showPdfParseDialog">
              <el-icon><Document /></el-icon>
              PDF解析
            </el-button>
          </el-space>
        </div>

        <!-- 文件列表区 -->
        <div class="file-lists">
          <el-row :gutter="20">
            <!-- 文件上传列表 -->
            <el-col :span="12">
              <el-card class="list-card">
                <template #header>
                  <div class="card-header">
                    <span>文件上传列表</span>
                    <el-button text @click="loadUploadedFiles">
                      <el-icon><Refresh /></el-icon>
                    </el-button>
                  </div>
                </template>
                <el-table
                  :data="uploadedFiles"
                  style="width: 100%"
                  height="500"
                  @row-contextmenu="handleContextMenu"
                >
                  <el-table-column prop="fileName" label="文件名" show-overflow-tooltip />
                  <el-table-column prop="fileSize" label="大小" width="100" />
                  <el-table-column prop="uploadTime" label="上传时间" width="180" />
                  <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                      <el-button 
                        v-if="isPdfFile(row.fileName)"
                        type="success" 
                        link 
                        @click="quickParsePdf(row)"
                      >
                        <el-icon><Document /></el-icon>
                        解析
                      </el-button>
                      <el-button type="primary" link @click="handleDownload(row)">
                        <el-icon><Download /></el-icon>
                        下载
                      </el-button>
                      <el-button type="danger" link @click="handleDelete(row)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>

            <!-- 文件转换列表 -->
            <el-col :span="12">
              <el-card class="list-card">
                <template #header>
                  <div class="card-header">
                    <span>文件转换列表</span>
                    <el-button text @click="loadConvertedFiles">
                      <el-icon><Refresh /></el-icon>
                    </el-button>
                  </div>
                </template>
                <el-table
                  :data="convertedFiles"
                  style="width: 100%"
                  height="500"
                  @row-contextmenu="handleContextMenu"
                >
                  <el-table-column prop="fileName" label="文件名" show-overflow-tooltip />
                  <el-table-column prop="fileType" label="类型" width="80" />
                  <el-table-column prop="convertTime" label="转换时间" width="180" />
                  <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                      <el-button type="primary" link @click="handleDownloadConverted(row)">
                        <el-icon><Download /></el-icon>
                        下载
                      </el-button>
                      <el-button type="danger" link @click="handleDeleteConverted(row)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>

    <!-- 文件上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      :title="uploadType === 'single' ? '单文件上传' : '多文件上传'"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :multiple="uploadType === 'multiple'"
        :limit="uploadType === 'multiple' ? 10 : 1"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            {{ uploadType === 'multiple' ? '可以选择多个文件（最多10个）' : '只能上传一个文件' }}
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- PDF解析对话框 -->
    <el-dialog
      v-model="pdfParseDialogVisible"
      title="PDF解析"
      width="600px"
    >
      <div v-if="pdfFiles.length === 0" class="empty-state">
        <el-empty description="暂无PDF文件">
          <el-button type="primary" @click="showUploadDialog('single')">上传PDF文件</el-button>
        </el-empty>
      </div>
      <el-form v-else :model="pdfParseForm" label-width="100px">
        <el-form-item label="选择文件">
          <el-select 
            v-model="pdfParseForm.selectedFile" 
            placeholder="请选择要解析的PDF文件"
            style="width: 100%"
          >
            <el-option
              v-for="file in pdfFiles"
              :key="file.id"
              :label="file.fileName"
              :value="file.filePath"
            >
              <div style="display: flex; justify-content: space-between;">
                <span>{{ file.fileName }}</span>
                <span style="color: #8492a6; font-size: 13px;">{{ file.fileSize }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导出格式">
          <el-radio-group v-model="pdfParseForm.exportFormat">
            <el-radio label="word">Word</el-radio>
            <el-radio label="excel">Excel</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pdfParseDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handlePdfParse" 
          :loading="parseLoading"
          :disabled="!pdfParseForm.selectedFile"
        >
          开始解析
        </el-button>
      </template>
    </el-dialog>

    <!-- 右键菜单 -->
    <el-dropdown
      ref="contextMenuRef"
      trigger="contextmenu"
      :virtual-ref="contextMenuVirtualRef"
      virtual-triggering
    >
      <span></span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="handleContextDownload">下载</el-dropdown-item>
          <el-dropdown-item @click="handleContextDelete" divided>删除</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  Upload,
  Document,
  Refresh,
  Download,
  Delete,
  UploadFilled
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { logout } from '@/api/auth'
import { uploadFile, uploadFiles, getFileList, deleteFile } from '@/api/file'
import { parsePdf } from '@/api/pdf'
import { downloadFile, getResultFiles } from '@/api/download'

const router = useRouter()
const userStore = useUserStore()

const uploadDialogVisible = ref(false)
const uploadType = ref('single')
const uploadRef = ref(null)
const pdfParseDialogVisible = ref(false)
const parseLoading = ref(false)
const uploadedFiles = ref([])
const convertedFiles = ref([])
const contextMenuRef = ref(null)
const contextMenuVirtualRef = ref(null)
const currentContextRow = ref(null)

const uploadUrl = computed(() => {
  return uploadType.value === 'single' ? '/api/file/upload' : '/api/file/upload/batch'
})

const uploadHeaders = computed(() => {
  return {
    'Authorization': `Bearer ${userStore.token}`
  }
})

const pdfParseForm = reactive({
  selectedFile: '',
  exportFormat: 'word'
})

// 计算属性：筛选出PDF文件
const pdfFiles = computed(() => {
  return uploadedFiles.value.filter(file => {
    const fileName = file.fileName.toLowerCase()
    return fileName.endsWith('.pdf')
  })
})

// 处理顶部菜单命令
const handleCommand = async (command) => {
  if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'logout') {
    try {
      await logout(true) // 静默模式，不显示错误消息
    } catch (error) {
      console.warn('调用登出API失败，但会清除本地登录状态:', error.message)
    } finally {
      // 无论API调用是否成功，都清除本地登录状态
      userStore.clearAuth()
      ElMessage.success('退出登录成功')
      router.push('/login')
    }
  }
}

// 显示上传对话框
const showUploadDialog = (type) => {
  uploadType.value = type
  uploadDialogVisible.value = true
}

// 显示PDF解析对话框
const showPdfParseDialog = () => {
  // 先加载文件列表，确保是最新的
  loadUploadedFiles(false)
  
  // 检查是否有PDF文件
  setTimeout(() => {
    const hasPdfFiles = uploadedFiles.value.some(file => 
      file.fileName.toLowerCase().endsWith('.pdf')
    )
    
    if (!hasPdfFiles) {
      ElMessage.warning('当前没有可解析的PDF文件，请先上传PDF文件')
    }
    
    pdfParseDialogVisible.value = true
  }, 200)
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success('文件上传成功')
    loadUploadedFiles()
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

// 加载已上传文件列表
const loadUploadedFiles = async (silent = false) => {
  try {
    const res = await getFileList({ page: 1, size: 100 }, silent)
    if (res.code === 200) {
      uploadedFiles.value = (res.data || []).map(file => ({
        id: file.id,
        fileName: file.originalFileName,
        fileSize: formatFileSize(file.fileSize),
        uploadTime: formatTime(file.uploadTime),
        filePath: file.filePath
      }))
    }
  } catch (error) {
    if (!silent) {
      console.warn('加载文件列表失败，请检查后端服务是否正常启动:', error.message)
    }
    uploadedFiles.value = []
  }
}

// 加载转换后文件列表
const loadConvertedFiles = async (silent = false) => {
  try {
    const res = await getResultFiles(silent)
    if (res.code === 200) {
      convertedFiles.value = (res.data || []).map(file => ({
        id: file.uuid,
        fileName: file.fileName,
        fileType: file.fileType,
        convertTime: formatTime(file.createTime),
        uuid: file.uuid
      }))
    }
  } catch (error) {
    if (!silent) {
      console.warn('加载转换文件列表失败，请检查后端服务是否正常启动:', error.message)
    }
    convertedFiles.value = []
  }
}

// 判断是否为PDF文件
const isPdfFile = (fileName) => {
  return fileName && fileName.toLowerCase().endsWith('.pdf')
}

// 快速解析PDF（从列表中直接点击）
const quickParsePdf = (file) => {
  pdfParseForm.selectedFile = file.filePath
  pdfParseDialogVisible.value = true
}

// PDF解析
const handlePdfParse = async () => {
  if (!pdfParseForm.selectedFile) {
    ElMessage.warning('请选择要解析的PDF文件')
    return
  }
  
  parseLoading.value = true
  try {
    const res = await parsePdf({
      filePath: pdfParseForm.selectedFile,
      exportFormat: pdfParseForm.exportFormat
    })
    
    if (res.status === 'SUCCESS') {
      ElMessage.success('PDF解析成功！')
      pdfParseDialogVisible.value = false
      // 重置表单
      pdfParseForm.selectedFile = ''
      pdfParseForm.exportFormat = 'word'
      // 刷新转换文件列表
      loadConvertedFiles()
    } else {
      ElMessage.error(res.error || 'PDF解析失败')
    }
  } catch (error) {
    console.error('PDF解析失败:', error)
    ElMessage.error('PDF解析失败，请检查文件格式')
  } finally {
    parseLoading.value = false
  }
}

// 下载文件
const handleDownload = async (row) => {
  try {
    const response = await downloadFile(row.fileName)
    downloadBlob(response.data, row.fileName)
  } catch (error) {
    ElMessage.error('文件下载失败')
    console.error('下载失败:', error)
  }
}

// 删除文件
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteFile(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadUploadedFiles()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 下载转换后的文件
const handleDownloadConverted = async (row) => {
  try {
    const response = await downloadFile(row.fileName)
    downloadBlob(response.data, row.fileName)
  } catch (error) {
    ElMessage.error('文件下载失败')
    console.error('下载失败:', error)
  }
}

// 删除转换后的文件
const handleDeleteConverted = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    loadConvertedFiles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 右键菜单
const handleContextMenu = (row, column, event) => {
  event.preventDefault()
  currentContextRow.value = row
  contextMenuVirtualRef.value = {
    getBoundingClientRect() {
      return {
        x: event.clientX,
        y: event.clientY,
        width: 0,
        height: 0,
        top: event.clientY,
        left: event.clientX,
        right: event.clientX,
        bottom: event.clientY
      }
    }
  }
}

const handleContextDownload = () => {
  if (currentContextRow.value) {
    handleDownload(currentContextRow.value)
  }
}

const handleContextDelete = () => {
  if (currentContextRow.value) {
    handleDelete(currentContextRow.value)
  }
}

// 下载Blob数据
const downloadBlob = (blob, fileName) => {
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  // 页面初始加载时使用静默模式，避免后端未启动时显示大量错误
  loadUploadedFiles(true)
  loadConvertedFiles(true)
  
  // 延迟3秒后再次尝试加载，如果后端启动慢
  setTimeout(() => {
    if (uploadedFiles.value.length === 0 && convertedFiles.value.length === 0) {
      loadUploadedFiles(true)
      loadConvertedFiles(true)
    }
  }, 3000)
})
</script>

<style scoped>
.home-container {
  width: 100%;
  height: 100vh;
  background: #f0f2f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  padding: 0 30px;
}

.header-left h2 {
  margin: 0;
  color: #333;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background 0.3s;
}

.user-info:hover {
  background: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #333;
}

.main-content {
  padding: 30px;
}

.operation-section {
  margin-bottom: 30px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  text-align: center;
}

.file-lists {
  width: 100%;
}

.list-card {
  height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-upload-dragger) {
  padding: 40px;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #409eff;
  margin-bottom: 16px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}
</style>




